package weibo.model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import net.rim.device.api.io.http.HttpDateParser;

import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import weibo.http.Response;
import code.StringUtility;

public class WeiboResponse 
{
	//private static Hashtable formatMap = new Hashtable();
    private transient int rateLimitLimit = -1;
    private transient int rateLimitRemaining = -1;
    private transient long rateLimitReset = -1;

    public WeiboResponse() {}

    public WeiboResponse(Response res) throws WeiboException
    {
        String limit;
        
		try
{
			limit = res.getResponseHeader("X-RateLimit-Limit");
	        if(limit!=null){rateLimitLimit = Integer.parseInt(limit);}
	        String remaining = res.getResponseHeader("X-RateLimit-Remaining");
	        if(remaining!=null){rateLimitRemaining = Integer.parseInt(remaining);}
	        String reset = res.getResponseHeader("X-RateLimit-Reset");
	        if(reset!=null){rateLimitReset = Long.parseLong(reset);}
		} catch (IOException e) {throw new WeiboException(e.toString());}
    }

    protected static void ensureRootNodeNameIs(String rootName, Element elem) throws WeiboException
    {
        if (!rootName.equals(elem.getNodeName()))
        {
            throw new WeiboException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
        }
    }

    protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws WeiboException
    {
        String actualRootName = elem.getNodeName();
        for(int i=0; i<rootNames.length; i++)
        {
            if(rootNames[i].equals(actualRootName)) {return;}
        }
        
        String expected = "";
        for (int i = 0; i < rootNames.length; i++) 
        {
            if (i != 0) 
            {
                expected += " or ";
            }
            expected += rootNames[i];
        }
        throw new WeiboException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
    }

    protected static void ensureRootNodeNameIs(String rootName, Document doc) throws WeiboException 
    {
        Element elem = doc.getDocumentElement();
        if (!rootName.equals(elem.getNodeName())) 
        {
            throw new WeiboException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/");
        }
    }

    protected static boolean isRootNodeNilClasses(Document doc)
    {
        String root = doc.getDocumentElement().getNodeName();
        return "nil-classes".equals(root) || "nilclasses".equals(root);
    }

    //protected static String getChildText( String str, Element elem ) {
    //    return HTMLEntity.unescape(getTextContent(str,elem));
    //}

    protected static String getTextContent(String str, Element elem)
    {
        NodeList nodelist = elem.getElementsByTagName(str);
        if (nodelist.getLength() > 0)
        {
            Node node = nodelist.item(0).getFirstChild();
            if (null != node)
            {
                String nodeValue = node.getNodeValue();
                return null != nodeValue ? nodeValue : "";
            }
        }
        return "";
     }

    /*modify by sycheng  add "".equals(str) */
    protected static int getChildInt(String str, Element elem) 
    {
        String str2 = getTextContent(str, elem);
        if (null == str2 || "".equals(str2)||"null".equals(str))
        {
            return -1;
        } else {
            return Integer.valueOf(str2).intValue();
        }
    }

    protected static long getChildLong(String str, Element elem) 
    {
        String str2 = getTextContent(str, elem);
        if (null == str2 || "".equals(str2)||"null".equals(str)) 
        {
            return -1;
        } else {
            return Long.parseLong(str2);
        }
    }

    protected static String getString(String name, JSONObject json, boolean decode) 
    {
        String returnValue = null;
            try {
                returnValue = json.getString(name);
                if (decode) {
                    try {
                        returnValue = new String(returnValue.getBytes(), "UTF-8");
                    } catch (UnsupportedEncodingException ignore) {
                    }
                }
            } catch (JSONException ignore) {}
        return returnValue;
    }

    protected static boolean getChildBoolean(String str, Element elem) {
        String value = getTextContent(str, elem);
        return value.equals("true") ? true : false;
    }
    //protected static long getChildDate(String str, Element elem) throws WeiboException {
    //   return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy");
    //}

    //protected static long getChildDate(String str, Element elem, String format) throws WeiboException {
    //    return parseDate(getChildText(str, elem),format);
    //}
    
    /**
     * 分析网页的日期数据，并生成适用的数据格式
     * @param str 日期字符串，格式为："Wdy, DD Mon YYYY, HH:MM:SS GMT"
     * @return 可识别的日期型数据
     */
    protected static Date parseDate(String str)
	{
		String[] datePart=StringUtility.split(str, " ");
		StringBuffer newDate=new StringBuffer();

		if(datePart.length==6)
		{
			newDate.append(datePart[0]+", ").append(datePart[2]+" ").append(datePart[1]+" ").append(datePart[5]+", ").append(datePart[3]+" ").append(datePart[4]);
			//newDate=new StringBuffer(sdf.formatLocal(HttpDateParser.parse(newDate.toString())));
		}
		
		return new Date(HttpDateParser.parse(newDate.toString()));
	}
    //protected static Date parseDate(String str, String format) throws WeiboException
    //{
    //	SimpleDateFormat sdf = (SimpleDateFormat) formatMap.get(format);
    //   if (sdf==null)
    //    {
    //        sdf = new SimpleDateFormat(format, Locale.getDefault());
    //        //sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    //        formatMap.put(format, sdf);
    //    }
        
    //    Date eventDate=new Date(HttpDateParser.parse(str));
        
    //    return eventDate;
    //}

    protected static int getInt(String key, JSONObject json) throws JSONException
    {
        String str = json.getString(key);
        if(null == str || "".equals(str)||"null".equals(str))
        {
            return -1;
        }
        
        return Integer.parseInt(str);
    }

    protected static long getLong(String key, JSONObject json) throws JSONException
    {
        String str = json.getString(key);
        if(null == str || "".equals(str)||"null".equals(str))
        {
            return -1;
        }
        
        return Long.parseLong(str);
    }
    
    protected static boolean getBoolean(String key, JSONObject json) throws JSONException
    {
        String str = json.getString(key);
        
        if(str==null || str.equals("") || str.equals("null")) {return false;}
        return str.equals("true") ? true : false;
    }

    public int getRateLimitLimit() {return rateLimitLimit;}

    public int getRateLimitRemaining() {return rateLimitRemaining;}

    public long getRateLimitReset() {return rateLimitReset;}
}